<?

//Initiate Authenticate
SecurityRedirect ();
//error_reporting(E_ALL);

/*
echo "<pre>";
print_r($_REQUEST);
echo "</pre>";
*/

//initiate Vars
define("PRIMARY_KEY","jo_id");
$FileName       = "ais_transaction_shipping_activity.php";
$FileTemplate   = "ais_transaction_shipping_activity_form.html";
$SubHeaderTitle = "Activity";
$TableName      = "tbljoborder";
$HTMLFormName   = "JOForm";
$PRIMARY_KEY    = PRIMARY_KEY;
$PRIMARY_VALUE  = GetParam($PRIMARY_KEY,"");

$MaxGrid        = "20";
$KTRASL                = GetOfficeID();
//$HTMLFormName2  = "BudgetForm";

$FormAction    = $FileName . "?" . AddParam(GetQueryString("QueryString", ""),"form","$HTMLFormName");
$FormEncType   = "application/x-www-form-urlencoded";
//$PMode         = "";

//Initiate Grid Fields;
$FormFields    = array("jo_id"=>"","jo_code"=>"","doc_ref"=>"","project_id"=>"","debtur"=>"","staff_id"=>"","jo_date"=>"date","rbt_idr"=>"","rbt_usd"=>"","rat_idr"=>"","rat_usd"=>"","jo_status"=>"","jo_appv_status"=>"");
buildsqlfield ("$TableName", $FormFields);


//Variable declaration
$jo_id = GetParam("jo_id","");
$project_id = GetParam("project_id","");

//Convert Date

$date_act= convert_date(GetParam("date_act",""));

//Convert Date


$today = date("Y-m-d");

list($day1,$month1,$year1) = explode("/",GetParam("commencing_delivery",""));
$commencing_delivery  = "$year1-$month1-$day1";

list($day2,$month2,$year2) = explode("/",GetParam("completed_delivery",""));
$completed_delivery  = "$year2-$month2-$day2";

//End Variable declaration


//buildsqlfield ("$TableName", $FormFields);

//Leave Here Untouch
$FormCName     = BuildHTMLField($FormFields,"name");
$FormCValue    = BuildHTMLField($FormFields,"value");
$FormHName     = BuildHTMLField($FormFields,"name",1);
$FormHValue    = BuildHTMLField($FormFields,"value",1);

//************ FORM ACTION **************


if (trim(GetParam("form",""))==trim($HTMLFormName)) {
    if (GetParam("FormAction","")=="Save") {
                      
            $DBConnection->dbc->query("DELETE FROM tblshipping_activity WHERE jo_id='".$jo_id."'");
            
            //Insert into tblshipping_doc_remarks
            FormSave("tblshipping_activity", "date_act", array("jo_id"=>"","activities_id"=>"","date_act"=>"date","to_act"=>"","uraian_act"=>"","from_act"=>""),"","jo_id","");

            $DBConnection->InsertGrid();
           
            $DBConnection->dbc->query("UPDATE ".$TableName." SET commencing_delivery='".$commencing_delivery."',completed_delivery='".$completed_delivery."',cargo_desc='".GetParam("cargo_desc","")."' WHERE jo_id='".$jo_id."'");
            
            SetLogActivity($TransNo,"Update","");
            
            //CheckAndUpdateCache ($TransNo);

        header("Location: $FileName?PageMode=Form&jo_id=$jo_id");
        exit;
    }
    if (GetParam("FormAction","")=="Delete") {
//      print "Deleted"."<br>\n";
                $SQL = "DELETE FROM tbljoborder WHERE jo_id='".GetParam("jo_id","")."'";
                $DBConnection->dbc->query($SQL);
                $SQL = "DELETE FROM tbljoactivity WHERE jo_id='".GetParam("jo_id","")."'";
                $DBConnection->dbc->query($SQL);
                SetLogActivity($TransNo,"Delete","");
        header("Location: $FileName?PageMode=Form");
        exit;
    }
}




//Field Verification
$Verification  = "False";
$SessionVar    = md5(microtime());
//$SessionVar    = "Stuck";


//$VerifyFields = array("services_id1" => "Services","qty1" => "Quantity","unit1"=>"Unit","curr1"=>"Currency","rate1"=>"Rate");

$VerifyFields = array();
VerifyHTML ($HTMLFormName,$VerifyFields,$SessionVar);


$InitFunction = "Masking();Masking2();";

$VerifyGrids = array();
$Masking1 = BuildMasking ($HTMLFormName,MutatorFields($FormFields,($MaxGrid+$Count)));
$Masking2 = BuildMasking ($HTMLFormName,array(),"2");
$JSMasks  = $Masking1.$Masking2;
Init($SessionVar,$JSMasks);
FormGridHTML ($HTMLFormName,$VerifyGrids,$Count,$MaxGrid,$SessionVar);



//************ SET FORM MODE ***************
$USER_CANPRINT_TAX="0";

if (GetParam(PRIMARY_KEY,"")) {
        $FormMode = "Edit";
        $USER_CANPRINT="1";
        $SQL ="SELECT vat FROM ais_memorial WHERE nobkt='".GetParam(PRIMARY_KEY,"")."' AND urut=999 ";
        if (strlen($DBConnection->dbc->get_var($SQL))) $USER_CANPRINT_TAX="1";
} else {
        $FormMode = "Add";
        $USER_CANPRINT="0";
}
//******* DATABASE GRID QUERY ***********

$SQL = "SELECT ".BuildFields($FormFields)." FROM `$TableName`";
if (GetParam(PRIMARY_KEY,"") && $FormMode="Edit") {
    $SQL      = $SQL."WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."'";
    $SQL     .= " AND ktrasl='".GetOfficeID()."'";
    $SQLGrid  = $SQL." ORDER BY urut";
}

//******* SHOW FORM CONTENT *********
$TBS = new clsTinyButStrong ;
$TBS->LoadTemplate($MOD_TEMPLATE_DIR."/".$FileTemplate);

//********************************* HTML Header ******************************************


//edited by Adit van Smith



//Project Get Header






if(GetParam(PRIMARY_KEY,"") != '' && GetParam(PRIMARY_KEY,"") != 'AUTO NUMBERED BY SYSTEM')
{  
   $SQLProject = "SELECT a.*,b.*,c.*,d.*, 
			      if(a.jo_appv_status = 'draft', 'Draft', if(a.jo_appv_status = 'wait_approved', 'Wait for Approval', if(a.jo_appv_status = 'approved', 'Approved', 'No Approval Status'))) as approval_status 
			      FROM `$TableName` as a ";
   $SQLProject.= "JOIN tblproject as b ON a.project_id = b.project_id "; 
   $SQLProject.= "JOIN ".$DBGeneral.".tblstaff as c ON a.staff_id = c.staff_id ";
   $SQLProject.= "JOIN tbldebtur as d ON a.debtur = d.CUCODE ";
   $SQLProject.= "WHERE a.".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY a.".PRIMARY_KEY." ASC";

   $ResultProject  = $DBConnection->dbc->get_results($SQLProject,ARRAY_A);   
   
   
   $SQLProject2 = "SELECT * FROM tblshipping_doc 
                   WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY shipping_doc_id ASC";

   $ResultProject2  = $DBConnection->dbc->get_results($SQLProject2,ARRAY_A);   
   
   if(empty($ResultProject2))
   {
	   $ResultProject2 = array(
	   
	       array(
	          
	          "port_loading" => "",
	          "charges_port"=>"",
	          "delivery_site"=>"",
	          "laks_cc"=>"",
	          "pros_by"=>"",
	          "voy"=>"",
	          "etd"=>$today,
	          "eta"=>$today,
	          "gdg"=>"",
	          "kins"=>"",
	          "hawe_no"=>"",
	          "hawe_no_ori"=>$today,
	          "hawe_no_cpy"=>$today,
	          "bl_no_ori"=>$today,
	          "bl_no_cpy"=>$today,
	          "invoice_no_ori"=>$today,
	          "invoice_no_cpy"=>$today,
	          "packing_list"=>"",
	          "packing_list_ori"=>$today,
			  "packing_list_cpy"=>$today,
			  "cert"=>"",
			  "cert_ori"=>$today,
			  "cert_cpy"=>$today,
			  "insurance"=>"",
			  "insurance_ori"=>$today,
			  "insurance_cpy"=>$today,
			  "loa"=>"",
			  "loa_ori"=>$today,
			  "loa_cpy"=>$today,
			  "stat_con"=>"",
			  "stat_con_ori"=>$today,
			  "stat_con_cpy"=>$today
	          	       
	       )
	   
	   );
	   
	   
   }
   
      
}

else
{
   $ResultProject  = array(	
      array(

         "jo_id" => "",
         "jo_code" => "",
         "doc_ref" => "",
         "project_id" => "",
         "debtur" => "",
         "staff_id" =>"",
         "jo_date" =>$today,
         "bl_no" => "",
         "invoice_no" => "",
         "vessel" => "",
         "rbt_idr" =>"",
         "rbt_usd" =>"",
         "rat_idr" =>"",
         "rat_usd" =>"",
         "jo_appv_status" =>"",
         "commencing_delivery"=>"",
         "completed_delivery"=>"",
         "cargo_desc"=>""

      )
   );

   //SELECT * FROM INFORMATION_SCHEMA.Columns where TABLE_NAME = 'Foo'

}


//Project

$shipment_arr = explode(".",$ResultProject[0]['jo_code']);
$shipment = $shipment_arr[2];

$HeaderFields = array("jo_id"=>"","jo_code"=>"","project_id"=>"project_id","debtur"=>"debtur","staff_id"=>"staff_id","jo_date"=>"date","rbt_idr"=>"","rbt_usd"=>"","rat_idr"=>"","rat_usd"=>"","jo_appv_status" => "");

//Leave Here Untouch
$FormHName     = BuildHTMLField($HeaderFields,"name",1);
$FormHValue    = BuildHTMLField($HeaderFields,"value",1);

$SQLHeader     = "SELECT ".BuildFields($HeaderFields)." FROM $TableName ";


// HTML Value
$TBS->MergeBlock("headbln",$FormHName);
$TBS->MergeBlock("headblv",$ResultProject);
$TBS->MergeBlock("headblv2",$ResultProject2);


//********************************* HTML GRID *********************************************
//HTML Grid

$SQLGrid = "SELECT * FROM tblshipping_activity as a
            LEFT JOIN tblactivity_setup as b ON a.activities_id = b.act_nr_id     
            WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY act_ship_id ";


$Result  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A);
$Result  = BuildEmptyGrid ($FormFields, $MaxGrid, $Result);


//Flag For Delcer Button
//$flag = CheckforDelcer($jo_id);


$TBS->MergeBlock("blg",$Result);
$TBS->Show();

//*************** ACTION FUNCTION *******************

function changeArrtoList($arr,$str)
{
	$arr_result = array();
		
	foreach($arr as $it => $val)
	{
	  $arr_delcer[] = $val[$str];	
	   
	}
	
	return $arr_delcer;
}


function CheckforDelcer($jo_id)
{   
    global $DBConnection; 
    
    $Delcer = "failed";
     
	//Check For Delcer
	$SQLGrid = "SELECT * FROM tblshipping_activity as a
				LEFT JOIN tblactivity_setup as b ON a.activities_id = b.act_nr_id     
				WHERE ".PRIMARY_KEY." ='".GetParam(PRIMARY_KEY,"")."' ORDER BY act_ship_id ";
	
	$ResultCheckDelcer  = $DBConnection->dbc->get_results($SQLGrid,ARRAY_A); 
    
    $arrCheckDelcer = changeArrtoList($ResultCheckDelcer,'activities_id');



	$SQLDelcerList = " SELECT b.activities_id FROM tbljoactivity as a
					   JOIN tbljoborder_costing as b ON a.services_id = b.services_id
					   WHERE a.jo_id ='".$jo_id."' ";

	$ResultDelcerList  = $DBConnection->dbc->get_results($SQLDelcerList,ARRAY_A);
	
	$arrDelcerList = changeArrtoList($ResultDelcerList,'activities_id');
	 
	 
	//Check For Delcer
	
	/*
	foreach($arrDelcerList as $id => $val)
	{
	    if(!in_array($val['activities_id'],$arrCheckDelcer))
	    {
			
		}
	}
	*/
	
}


function FormInsert() {
        global $DBConnection,$FileName;
        $DBConnection->Insert();
        header("Location: $FileName?PageMode=Form");
        exit;
}

function FormUpdate() {
        global $DBConnection;
        $DBConnection->Update();
}

function FormDelete() {
        global $DBConnection,$FileName,$TableName;
        $DBConnection->deleteGrid("$TableName","nobkt");
        header("Location: $FileName");
        exit;
}

function FormSearch () {

}

function FormCancel () {
        global $FileName;
        header("Location: ".$FileName."?PageMode=List");
        exit;
}


function FormSave ($table, $keyField, $FormFields, $SpecialCase="", $PrimaryKey, $PrimaryKeyVal="") {	    
        global $FileName, $MaxGrid, $DBConnection;
        $TotalData = $MaxGrid * 2;
        $NewDataStart = GetParam("NewData","0");
        $NewDataStart = 1;

		  //echo(GetParam("jo_id",""));exit;
		  $alljo=GetParam("jo_id","");
 		  $DBConnection->dbc->query("update tbljoborder_costing set work_flag=0, work_flag_modified='0000-00-00 00:00:00' where jo_id=".$alljo.";");


        for ($a=1;$a<=$MaxGrid;$a++) {
	    //Begin For

            
            if (GetParam($keyField.$a,""))
            {
			//Begin Check if Empty Keyfield	
            
                 
                foreach ($FormFields as $key=>$formatting) {



                        if(!empty($PrimaryKeyVal))
                        {

                            $value = GetParam($key.$a,"");

                            if ($formatting=="number") $value = str_replace(",","",$value);
                            if ($formatting=="date")
                            {
                                    list($day,$month,$year) = explode("/",$value);
                                    $value = "$year-$month-$day";
                            }
                            //Inser if the key is equal primary key, then set valu = primary header
                            if($key == "$PrimaryKey")
                            {
                               $DBConnection->add_data($table,$key,$PrimaryKeyVal);
                            }

                            else
                            {
                               $DBConnection->add_data($table,$key,$value);
                            }

                        }

                        else
                        {
                            
                            $value = GetParam($key.$a,"");

                            if ($formatting=="number") $value = str_replace(",","",$value);
                            if ($formatting=="date")
                            {
                                    list($day,$month,$year) = explode("/",$value);
                                    $value = "$year-$month-$day";
                            }

                            $DBConnection->add_data($table,$key,$value);

                        }

								if($key=='jo_id') { $jo_id[$a]=$value; }
								if($key=='activities_id') { $activities_id[$a]=$value; }
                        
                }

			 		 $DBConnection->dbc->query("update tbljoborder_costing set work_flag=1, work_flag_modified='".date('Y-m-d g:i:s')."' where jo_id=".$jo_id[$a]." AND activities_id=".$activities_id[$a].";");

                $rate = StrToNumber(GetParam("rate",""));
                $jmh  = StrToNumber(GetParam("jumlah".$a,""));

                // Add by Chandra (15 May 2009)
                $cash_type = GetParam("cash_type","");
                //var_dump($cash_type); exit;



                if($cash_type) $DBConnection->add_data($table,'cash_type',$cash_type);
                // end update


                if (strlen($SpecialCase)) 
                {
                        
                        foreach ($SpecialCase as $key => $value) 
                        {
                                 
                                //print "add_data($table,$key,$value);<br>";
                                $DBConnection->add_data($table,$key,$value);
                        }
                }

//                print "$a < $NewDataStart<br>";
                if ($a < $NewDataStart) 
                {
                         if (strlen($PrimaryKey)) 
                         {
                            $DBConnection->UpdateGrid($PrimaryKey,GetParam($PrimaryKey.$a,""));
                         } 
                         else 
                         {
                            $DBConnection->UpdateGrid($keyField,GetParam($keyField.$a,""));
                         }
                } 
                
                else 
                {
                        $DBConnection->InsertGrid();
//                        $DBConnection->dbc->debug();
                }
            
            
            //End Check if Empty Keyfield
            }
            
            
        //End For    
        }
        $DBConnection->ClearData();
}


//*************** USER FUNCTION *******************

function buildsqlfield ($table, $arrayfield) {
        global $DBConnection;
        foreach ($arrayfield as $key=>$Formatting) {
            $value = GetParam($key,"");
            if ($Formatting=="date") {
                list($day,$month,$year) = explode("/",$value);
                $value = "$year-$month-$day";
            } elseif ($Formatting=="number") $value = str_replace(",","",$value);
            $DBConnection->add_htmlfield($table,$key,$value);
        }
}


function DeleteRecord ($sequence_name,$PageSize) {
        global $DBConnection,$FileName,$TableName;
        for ($x=1;$x<=$PageSize;$x++) {
                if (GetParam($sequence_name.$x,""))        {
                        $DBConnection->deleteGrid("$TableName","memorial_id",$sequence_name.$x);
            }
        }
}

function BuildFields ($FormFields) {
                global $DBConnection;
                $str = "";
                foreach ($FormFields as $key=>$formatting) {
                        if (strlen($str)) $str .= ",$key";
                        else $str = "$key";
                }
                return $str;
}

function MutatorFields ($FormFields, $MaxGrid) {
                global $DBConnection;
                $array_fields = array();
                for ($x=0;$x<$MaxGrid;$x++) {
                        foreach ($FormFields as $key=>$formatting){
                                $a=$x+1;
                                $array_fields[$key.$a] = "$formatting";
                        }
                }
                return $array_fields;
}

function FlushCustomer ($TableName, $tmp) {
        global $DBConnection;

        if ($tmp) $TEMPORARY = "TEMPORARY";
        $DBC = new mydb(DB_USER, DB_PASSWORD, DB_NAME2, DB_HOST);

        $SQL = "SELECT kodecustomer,nama,cr_term,kdtype FROM customer ";
        if (GetParam("kdtype","")) $SQL .= " WHERE kdtype='".GetParam("kdtype","")."'";
        $MyResult = $DBC->dbc->get_results($SQL,ARRAY_N);
        if (!$MyResult) return false;
         $session_file = substr(md5(time()), 0, 8);
           $session_file = "/tmp/".$session_file.".tmp";
        BufferToFile ($MyResult,$session_file);

        $DBConnection = new mydb(DB_USER, DB_PASSWORD, DB_NAME, DB_HOST);
        $SQL = "DROP TABLE IF EXISTS `$TableName`;";
        $DBConnection->dbc->query($SQL);

        $SQL= "CREATE $TEMPORARY TABLE `$TableName` (
                          `kodecustomer` varchar(20) NOT NULL default '',
                          `nama` varchar(50) default NULL,
                          `cr_term` int(4) default NULL,
                          `kdtype` varchar(20) default NULL
                          )";
        $DBConnection->dbc->query($SQL);

           $SQL = "LOAD DATA INFILE '$session_file' INTO TABLE $TableName FIELDS TERMINATED BY '\t' LINES TERMINATED BY '\n'";
        $DBConnection->dbc->query($SQL);
        unlink($session_file);
        return true;
}

function GetLastDateReport() {
        global $DBConnection;
        list($day,$month,$year) = explode("/",GetParam("tglbkt",""));
        $current_date = "$year-$month-$day";

    $SQL = "DELETE FROM ais_piutang_sisa WHERE aging_date>='$current_date' ";
    if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
    if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";
    $DBConnection->dbc->query($SQL);
    //$DBConnection->dbc->debug();

        $SQL = "SELECT max(aging_date) FROM ais_piutang_sisa WHERE aging_date<='$current_date' ";
        if (GetParam("curr","")) $SQL .= " AND curr='".GetParam("curr","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND fromskada = '".GetParam("skada999","")."' ";
        if (GetParam("skada999","")) $SQL .= " AND toskada = '".GetParam("skada999","")."' ";

        return $DBConnection->dbc->get_var($SQL);
}

function convert_code($code,$digit)
{
		
	$length = strlen($code);	
	$tot_str = $digit - $length;	
	$code_edit = "";
	
	for($i=0;$i < $tot_str; $i++)
	{
		$code_edit.= "0";
	}
	
	$code_edit.= $code;
	
	return $code_edit;
	
}

function convert_date($dateVar)
{
	list($day,$month,$year) = explode("/",$dateVar);
    $dateResult  = "$year-$month-$day";	
    
    return $dateResult;
}



?>
